package rm.mk;

import java.util.ArrayList;
import java.util.List;

import rm.mk.data.City;
import rm.mk.data.Route;


public class CopyOfRouteFinder extends AbstractFinder {

	public CopyOfRouteFinder(List<City> cities) {
		super(cities);
	}

	public String findShortestRoute(int from, int to) {
		Meta low = C(from, to);
		
		StringBuilder sb = new StringBuilder(from + " do " + to + ": { ");
		
		int totalCost = 0;
		
		while(low != null)
		{
			sb.append(low.at + " -> " + (low.m == null ? to: low.m.at) + " cost(" + low.cost + "), ");
			totalCost += low.cost;
			
			low = low.m;
		}
		
		sb.append("}  = " + totalCost);
		
		return sb.toString();
	}
	
	private List<Meta> kosztyDo(int iAmAt, int cityNr){
		City at = this.selectCity(iAmAt);
		City dest = this.selectCity(cityNr);
		
		List<Meta> mt = new ArrayList<Meta>();
		
		for(Route r : at.getRoutes());
			
		return null;
	}
	
	private class Meta{
		
		private int cost, at;
		private Meta m;

		public Meta(int cost, Meta meta, int at) {
			this.cost = cost;
			this.at = at;
			this.m = meta;
		}
		
		public int getTotalCost()
		{
			if(m == null) return cost;
			
			return this.cost + m.getTotalCost();
		}
	}
	
	private Meta C(int at, int dest)
	{
		if(at == dest) return null;
		
		City att = this.selectCity(at);
		if(att == null) return null;
		if(att.getRoutes().size() == 0) return null;
		
		List<Meta> costs = new ArrayList<Meta>();
		
		for(Route r : att.getRoutes())
			costs.add(new Meta(r.getCost(), C(r.getDestination(), dest), at));
		
		return min(costs);
	}

	private Meta min(List<Meta> costs) {
		Meta lowestCost = costs.get(0);
		
		for(Meta m : costs)
			if(m.getTotalCost() < lowestCost.getTotalCost())
				lowestCost = m;
		
		return lowestCost;
	}
}
